package com.lucien.framework.websocket.interceptor;

import com.lucien.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.Map;

/**
 * 认证用户信息的握手拦截器
 */
@Component
public class MylHandshakeHandler extends HttpSessionHandshakeInterceptor {

    private static final Logger log = LoggerFactory.getLogger(MylHandshakeHandler.class);


    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        HttpSession session = getSession(request);
        log.info("用户握手拦截：" + session.toString());
        if (StringUtils.isNotNull(session)){
            //isCopyHttpSessionId(): 是否复制HTTP会话id到握手属性
            if (isCopyHttpSessionId()){
                // session.getId() 获取用户session
                attributes.put(HTTP_SESSION_ID_ATTR_NAME, session.getId());
            }
            Enumeration<String> names = session.getAttributeNames();
            while (names.hasMoreElements()){
                String element = names.nextElement();
                if (isCopyAllAttributes() || getAttributeNames().contains(element)){
                    attributes.put(element, session.getAttribute(element));
                }
            }
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
        log.info("握手完成");
        super.afterHandshake(request, response, wsHandler, ex);
    }

    private HttpSession getSession(ServerHttpRequest request) {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
            return serverRequest.getServletRequest().getSession(true);
        }
        return null;
    }



}
